# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import json
from common.utils.urls import UrlUtil
from common.utils.config import ConfigUtil
from apps.admin.schemas.square import setting_schema as schema


class SquareSettingService:

    @classmethod
    async def detail(cls) -> schema.SquareSetting:
        config = await ConfigUtil.get('square') or {}

        async def create_config_vo(section):
            return schema.SquareSetting.ConfigVo(
                is_open=int(section.get("is_open", "0")),
                is_user=int(section.get("is_user", "0")),
                audit_type=int(section.get("audit_type", "0")),
                name=section.get("name", ""),
                title=section.get("title", ""),
                banner=await UrlUtil.to_absolute_url(section.get("banner", ""))
            )

        return schema.SquareSetting(
            robot=await create_config_vo(config.get("robot") or {}),
            draws=await create_config_vo(config.get("draws") or {}),
            video=await create_config_vo(config.get("video") or {}),
            music=await create_config_vo(config.get("music") or {})
        )

    @classmethod
    async def save(cls, post: schema.SquareSetting):
        async def save_section(section_name, section_data, section_type):
            await ConfigUtil.set(
                "square",
                section_name,
                json.dumps({
                    "type": section_type,
                    "is_open": section_data.is_open,
                    "is_user": section_data.is_user,
                    "audit_type": section_data.audit_type,
                    "name": section_data.name,
                    "title": section_data.title,
                    "banner": UrlUtil.to_relative_url(section_data.banner)
                }, ensure_ascii=False)
            )

        await save_section("robot", post.robot, "robot")
        await save_section("draws", post.draws, "draws")
        await save_section("video", post.video, "video")
        await save_section("music", post.music, "music")
